/*************************************************************************
	> File Name: 003.重载[]运算符.cpp
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 五  1/ 7 10:48:02 2022
 ************************************************************************/

#include <iostream>
using namespace std;

class Point {
public:
    Point();
    Point(int x, int y);
    Point operator+(const Point&);
    Point& operator+=(int);
    int operator[](string);
private:
    friend Point operator+(const Point&, const Point&);
    friend ostream& operator<<(ostream& out, const Point&);
    int x, y;
};

Point::Point() : Point(0, 0) {  }
Point::Point(int x, int y): x(x), y(y) {  }

//类内重载+
Point Point::operator+(const Point& rhs) {
    return Point(this->x + rhs.x, this->y + rhs.y);
}

//类内重载+=
Point& Point::operator+=(int val) {
    x += val;
    y += val;
    return *this;
}

//类内重载[]
int Point::operator[](string s) {
    if (s == "x") return x;
    if (s == "y") return y;
    return 0;
}

//类外重载+
Point operator+(const Point& lhs, const Point& rhs) {
    return Point(lhs.x + rhs.x, lhs.y + rhs.y);
}

ostream& operator<<(ostream& out, const Point& rhs) {
    out << "(" << rhs.x << ", " << rhs.y << ")";
    return out;
}

int main() {
    Point p1(3, 4);
    Point p2(7, 9);
    cout << p1["x"] << endl; //3
    cout << p1["y"] << endl; //4

    Point p3 = p1 + p2;
    cout << p1 << endl;//(3, 4)
    cout << p2 << endl;//(7, 9)
    cout << p3 << endl;//(10, 13)

    p1 += 2;
    cout << p1 << endl;//(5, 6)
    return 0;
}
